package com.zkgengkun.console.controller;

import com.google.common.collect.Maps;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.zkgengkun.console.service.BlogService;
import com.zkgengkun.console.service.UploadService;
import com.zkgengkun.constant.SysConstants;
import com.zkgengkun.dao.mybatis.CommDAO;
import com.zkgengkun.domain.Admin;
import com.zkgengkun.domain.Blog;
import com.zkgengkun.domain.Division;
import com.zkgengkun.repository.AdminRepository;
import com.zkgengkun.repository.DivisionRepository;
import com.zkgengkun.repository.RoleRepository;
import com.zkgengkun.support.component.AmqpSend;
import com.zkgengkun.support.component.AsyncExecutor;
import com.zkgengkun.support.component.KdApiOrderDistinguish;
import com.zkgengkun.support.io.rong.RongCloud;
import com.zkgengkun.support.io.rong.messages.TxtMessage;
import com.zkgengkun.support.io.rong.models.ChatRoomInfo;
import com.zkgengkun.support.io.rong.models.CodeSuccessResult;
import com.zkgengkun.support.io.rong.models.TokenResult;
import com.zkgengkun.support.json.Jacksons;
import com.zkgengkun.support.util.*;
import org.apache.commons.lang.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author gengshikun
 * @date 2016/12/6
 */
@Controller
public class WebIndexController {

    private static final Logger logger = LoggerFactory.getLogger(WebIndexController.class);

    @Autowired
    private AmqpSend amqpSend;

    @Autowired
    private BlogService blogService;

    @Autowired
    private KdApiOrderDistinguish kdApiOrderDistinguish;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private AsyncExecutor asyncExecutor;

    @RequestMapping(value = {"", "/index"}, method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @RequestMapping(value = "test/url")
    @ResponseBody
    public String testUrl(String url) {
        this.uploadService.uploadJpgByUrl(url);
        return "success";
    }

    @RequestMapping(value = "test/s_randmember")
    @ResponseBody
    public String testSrandmember(Integer count) {
        List<String> set = JedisUtil.getInstance().SETS.srandmember("test-s_add", count == null ? 1 : count);
        JedisUtil.getInstance().SETS.srem("test-s_add", set.toArray(new String[]{}));
        return Jacksons.json().fromObjectToJson(set);
    }

    @RequestMapping(value = "test/s_add")
    @ResponseBody
    public String testSadd(String value) {
        for (int i = 0; i < 100; i++) {
            JedisUtil.getInstance().SETS.sadd("test-s_add", i + "");
        }
        return "success";
    }

    @RequestMapping(value = "test/amqp", method = RequestMethod.GET)
    public String testKd() {
        amqpSend.sendMsg("Hello Springboot!");
        Map<String, Object> map = Maps.newHashMap();
        map.put("hello", "Hello Map!");
        amqpSend.sendMap(SysConstants.AMQP_ROUTINGKEY_MAP, map);
        return "index";
    }

    @RequestMapping(value = "test/kd", method = RequestMethod.GET)
    public String testAmqp() {
        try {
            String result = kdApiOrderDistinguish.getOrderTracesByJson("308552291983");

//            Map map = Jacksons.json().fromJsonToMap(result);
//            List list = (List) map.get("Shippers");
//            Map ship = (Map) list.get(0);

            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }


    @RequestMapping(value = "test/exception_json", method = RequestMethod.GET)
    public String json() throws Exception {
        throw new NullPointerException();
    }

    @RequestMapping(value = "test/json", method = RequestMethod.GET)
    public ModelAndView testJson() throws Exception {
        ModelAndView model = new ModelAndView();
        // 转Json
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        model.setView(jsonView);
        model.addObject("status", Boolean.FALSE);
        model.addObject("msg", "失败");
        return model;
    }

    @RequestMapping(value = "test/redis", method = RequestMethod.GET)
    @ResponseBody
    public String testRedis() {

        JedisUtil.getInstance().STRINGS.setEx("boot-test", 100, "redis-test");

        String test = JedisUtil.getInstance().STRINGS.get("boot-test");
        System.out.println(test);

        return "success";
    }

    @RequestMapping(value = "test/redis_service")
    @ResponseBody
    public Map testRedisService(Model model) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("blog1", this.blogService.getOne("402881a65aa6cfa1015aa6d3cb350000").getBlogId());
        return result;
    }

    @RequestMapping(value = "test/redis_test")
    @ResponseBody
    public String testRedisTest() {
        Blog blog = this.blogService.getOneByTitle("testRedis");
        return blog.getTitle();
    }

    @RequestMapping(value = "test")
    public String test() {
        return "test";
    }

    @RequestMapping(value = "test/thread")
    public String testThread() {
        logger.info("test-thread start");
        for (int i = 1; i <= 50; i++) {
            this.asyncExecutor.test1(i);
        }

        return "index";
    }

    @RequestMapping(value = "test/delaymq")
    public String testDelayMQ() {
        Map<String, String> test = Maps.newHashMap();
        test.put("123", "aaa");
        amqpSend.sendDelayMap(test, -5);

        return "index";
    }

    @RequestMapping(value = "520", method = RequestMethod.GET)
    public String ILU() {
        return "520";
    }

    @RequestMapping(value = "520", method = RequestMethod.POST)
    public String ILUPOST() {
        return "520";
    }

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private AdminRepository adminRepository;

    @RequestMapping(value = "test/toTable")
    public String testToTable(){
        Admin admin = new Admin();
        admin.setUsername("test3");
        admin.setPassword("test3");
        admin.setRoleList(Arrays.asList(this.roleRepository.findOne("1")));

//        this.adminRepository.save(admin);

//        List<Admin> list = this.adminRepository.getByRoleList(Arrays.asList("1"));
        List<Admin> list = this.adminRepository.findByRoleList(Arrays.asList(this.roleRepository.findOne("1")));
        System.out.println(list);

        return "index";
    }

    @Autowired
    private CommDAO commDAO;

    @RequestMapping(value = "test/mybatis")
    public String testMybatis(){

//        Admin admin = this.adminRepository.getOne("402881a65d07a186015d07a2003b0001");
//        System.out.println(admin);

        return "index";
    }

    @Autowired
    private DivisionRepository divisionRepository;

    /**
     * 爬 行政区划
     * @return
     */
    @RequestMapping(value = "test/division")
    public String testDivision(){
        Document doc = null;
        try {
            doc = JsoupUtil.getDocument("http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201703/t20170310_1471429.html");
            Elements elements = doc.getElementsByClass("TRS_PreAppend");
            Elements list = elements.get(0).children();

            for(Element one : list){
                if(StringUtils.isNotBlank(one.getElementsByTag("b").toString())){
                    Division division = new Division();

                    // 省
                    String aCode = one.getElementsByAttributeValue("lang", "EN-US").get(0).ownText();
                    String aName = one.getElementsByAttributeValue("style", "font-family: 宋体").get(0).ownText();
                    System.out.println(aCode + " : " + aName);
                    division.setId(aCode);
                    division.setType("1");
                    division.setName(aName);
//                    divisionRepository.save(division);
                    amqpSend.sendMap(BeanUtils.transBean2Map(division));

                    one = one.nextElementSibling();
                    String cCode = "";
                    while (null != one && StringUtils.isBlank(one.getElementsByTag("b").toString())) {
                        // 市
                        if(one.child(0).text().length() == 1){
                            cCode = one.getElementsByAttributeValue("lang", "EN-US").get(0).ownText();
                            String cName = one.getElementsByAttributeValue("style", "font-family: 宋体").get(1).ownText().substring(1);
                            System.out.println("  " + cCode + " : " + cName);
                            division = new Division();
                            division.setId(cCode);
                            division.setPid(aCode);
                            division.setType("2");
                            division.setName(cName);
                            //                    divisionRepository.save(division);
                            amqpSend.sendMap(BeanUtils.transBean2Map(division));
                        }

                        // 区/县
                        one = one.nextElementSibling();
                        if(one.child(0).text().length() == 2){
                            String bCode = one.getElementsByAttributeValue("lang", "EN-US").get(0).ownText();
                            String bName = one.getElementsByAttributeValue("style", "font-family: 宋体").get(1).ownText().substring(2);
                            System.out.println("    " + bCode + " : " + bName);
                            division = new Division();
                            division.setId(bCode);
                            division.setPid(cCode);
                            division.setType("3");
                            division.setName(bName);
                            //                    divisionRepository.save(division);
                            amqpSend.sendMap(BeanUtils.transBean2Map(division));
                        }
                        one = one.nextElementSibling();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "index";
    }

    private static String appKey = "p5tvi9dspmuc4";
    private static String appSecret = "nutfSc9XIBy04";
    private static RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);

    @RequestMapping(value = "test/chatroom")
    @ResponseBody
    public String testChatroom() throws Exception {
        // 创建聊天室方法
        ChatRoomInfo[] chatroomCreateChatRoomInfo = {
                new ChatRoomInfo("chatroomId1","chatroomName1" ),
                new ChatRoomInfo("chatroomId2","chatroomName2" ),
                new ChatRoomInfo("chatroomId3","chatroomName3" )};
        CodeSuccessResult chatroomCreateResult = rongCloud.chatroom.create(chatroomCreateChatRoomInfo);
        System.out.println("create:  " + chatroomCreateResult.toString());
        return "success";
    }

    @RequestMapping(value = "test/chatroom/destroy")
    @ResponseBody
    public String destroyChatroom(String chatroomId, String message) {
        // 销毁聊天室方法
        String[] chatroomDestroyChatroomId = {"59a38e340d4efc0a10ec68b4"};
        CodeSuccessResult chatroomDestroyResult = null;
        try {
            chatroomDestroyResult = rongCloud.chatroom.destroy(chatroomDestroyChatroomId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("destroy:  " + chatroomDestroyResult.toString());
        return "success";
    }

    @RequestMapping(value = "test/rongyun")
    public String testRongYun(Model model) throws Exception {

        String userId = "shik";
        String username = "Shik";

        // 获取 Token 方法
        TokenResult userGetTokenResult = rongCloud.user.getToken(userId, username, "http://www.rongcloud.cn/images/logo.png");
        System.out.println("getToken:  " + userGetTokenResult.toString());

        model.addAttribute("userId", userId);
        model.addAttribute("username", username);
        model.addAttribute("token", userGetTokenResult.getToken());
        model.addAttribute("appKey", appKey);
        model.addAttribute("chatroomId", "59a1197abeb62542d05ed577");
        return "rongyun";
    }

    @RequestMapping(value = "test/rongyun1")
    public String testRongYun1(Model model) throws Exception {

        String userId = "b2b2b2b2";
        String username = UUIDUtils.random16UUID();

        // 获取 Token 方法
        TokenResult userGetTokenResult = rongCloud.user.getToken(userId, username, "http://www.rongcloud.cn/images/logo.png");
        System.out.println("getToken:  " + userGetTokenResult.toString());

        model.addAttribute("userId", userId);
        model.addAttribute("username", username);
        model.addAttribute("token", userGetTokenResult.getToken());
        model.addAttribute("appKey", appKey);
        model.addAttribute("chatroomId", "chatroomId1");
        return "rongyun";
    }

    @RequestMapping(value = "test/message")
    @ResponseBody
    public String adminMessage(String chatroomId, String message) {
        String[] messagePublishChatroomToChatroomId = {"chatroomId1"};
        Map<String, String> extra = Maps.newHashMap();
        extra.put("name", "shik");
        extra.put("icon", "/images/logo.png");
        TxtMessage messagePublishChatroomTxtMessage = new TxtMessage(message, Jacksons.json().fromObjectToJson(extra));
        try {
            this.rongCloud.message.publishChatroom("a1a1a1a1", messagePublishChatroomToChatroomId, messagePublishChatroomTxtMessage);
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>>>>>>>>>>>>>> rongcloud admin发送消息失败, chatroomId: {} >>>>>>>>>>>>>>>>>>>>", chatroomId);
        }
        return "success";
    }


}
